/**
 * @description 瓦片服务
*/

const { JSONFile } = require('@daelui/oxkit/dist/index.js')
const Service = require('../service.js')
const Tianditu = require('./tianditu.js')
const Autonavi = require('./autonavi.js')
const ArcGis = require('./arcgis.js')
const config = global.config
const tile = config.tile || {}
const maps = tile.maps || []

// 下载器集合
const loaderEntries ={
  tianditu: Tianditu,
  autonavi: Autonavi,
  arcgis: ArcGis
}

// 瓦片服务
class Tile extends Service {
  constructor () {
    super()
    this.tasks = []
  }

  // 创建任务
  createTask (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      let result = null
      // 参数检查
      let layers = Array.isArray(params.layers) ? params.layers : []
      // 获取有效的图层
      let allowLayers = layers.filter(item => {
        let b = false
        maps.forEach(node => {
          if (node.map === item.map){
            let matched = node.layers.find(layer => layer.layer === item.layer && layer.path === item.path)
            if (matched) {
              b = true
              item.mapProvider = node
              item.layerProvider = matched
            }
          }
        })
        return b
      })
      if (!params.layers || params.layers.length < 1) {
        result = this.result({
          success: 0,
          msg: '未选择地图图层'
        })
      } else if (allowLayers.length < 1) {
        result = this.result({
          success: 0,
          msg: '不支持该地图瓦片下载'
        })
      } else if (!params.range || params.range.length !== 4) {
        result = this.result({
          success: 0,
          msg: '坐标范围不完整'
        })
      } else if (!params.levels || params.levels.length < 1) {
        result = this.result({
          success: 0,
          msg: '未选择地图级别'
        })
      }
      if (result) {
        return result
      }

      // 开始任务
      allowLayers.forEach(item => {
        this.start(item, params)
      })

      return this.result({
        success: 1,
        msg: '任务执行中'
      })
    })
  }

  // 下载地图
  start (layer, params) {
    let Loader = loaderEntries[layer.map]
    if (Loader) {
      let task = new Loader({
        params: params,
        layer: layer
      })
      this.tasks.push(task)
      task.run()
    }
  }

  // 停止
  stop (req) {
    return this.solveRequest(req).then(data => {
      let params = data.params || {}
      this.tasks.forEach(item => {
        item.stop()
      })
      return this.result({
        success: 1,
        msg: '操作成功'
      })
    })
  }

  // 查询任务
  query () {
    let res = new JSONFile().read(tile.taskPath + '/tile_db.json')
    let data = res.data || []
    return this.result({
      success: 1,
      msg: '成功',
      data
    })
  }
}

module.exports = Tile